
var app = getApp()
const recorderManager = wx.getRecorderManager();
var getAppGlobalData = require('../../../templates/copyright/copyright.js');
// var getRecordAuth = require('../../../templates/record/record.js');
Page({
  data: {
    setJob: [],
    job: -1,
    playPushStatus: 1,
    startPushStatus: 1,
    recordAuthMethod: 2,
    globalData: {},
    uploadUrl: '',
    tempRecordFilePath: '',
    tempRecordFileTime: '',
    recordStatusText: '开始录音 按住说话',
    staffInfo: [],
    currentIndex: 0,
    staffInfoAvatar: '',
    staffInfoImages: [],
    recordStatus: true,
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数 
    var that = this;
    // <!-- {{startPushStatus == 1 ? '开始' : '停止'}}录音 -->

    wx.hideShareMenu();
    getAppGlobalData.getAppGlobalData(that);


    // that.getCheckAuthRecord();
    that.getStaffJob();
    that.getStaffCard();

    var tmpRecordStatusText = '';
    if (that.data.staffInfo.voice) {
      tmpRecordStatusText = '重新录音 按住说话'
    } else if (!that.data.staffInfo.voice) {
      tmpRecordStatusText = '开始录音 按住说话'
    }
    that.setData({
      globalData: app.globalData,
      recordStatusText: tmpRecordStatusText
    })

    var uploadUrl = app.util.url('entry/wxapp/upload');
    var nowPage = getCurrentPages();
    if (nowPage.length) {
      nowPage = nowPage[getCurrentPages().length - 1];
      if (nowPage && nowPage.__route__) { 
        uploadUrl = uploadUrl + '&m=' + nowPage.__route__.split('/')[0];
      }
    }
    that.setData({
      uploadUrl: uploadUrl
    })
  },
  onReady: function () {
    // console.log("页面渲染完成")
  },
  onShow: function () {
    // 页面显示 
    var that = this;

    if (that.data.recordAuthMethod == 1) {

      wx.getSetting({
        success: function (res) {
          if (res.authSetting['scope.record']) {
            console.log('onshow已经授权')
            that.setData({
              recordAuthMethod: 2
            })
          } else {
            that.setData({
              recordAuthMethod: 1
            })
          }
        },
        fail: function (res) {
          console.log('onshow未授权')
          that.setData({
            recordAuthMethod: 1
          })
        }
      })

      var tmpRecordStatusText = '';
      if (that.data.staffInfo.voice) {
        if (that.data.recordAuthMethod == 1) {
          tmpRecordStatusText = '重新录音 按住说话'
        } else if (that.data.recordAuthMethod == 2) {
          tmpRecordStatusText = '重新录音 按住说话'
        }
      } else if (!that.data.staffInfo.voice) {
        if (that.data.recordAuthMethod == 1) {
          tmpRecordStatusText = '开始录音 按住说话'
        } else if (that.data.recordAuthMethod == 2) {
          tmpRecordStatusText = '开始录音 按住说话'
        }
      }
      that.setData({
        recordStatusText: tmpRecordStatusText
      })
    }
  },
  onHide: function () {
    // console.log("页面隐藏")
  },
  onUnload: function () {
    // console.log("页面关闭")
  },
  onPullDownRefresh: function () {
    // console.log("监听用户下拉动作")  
  },
  onReachBottom: function () {
    // console.log("监听页面上拉触底")  
  },
  onPageScroll: function (e) {
    //console.log("监听页面滚动", e);
  },
  onShareAppMessage: function (res) {
    // console.log("用户点击右上角分_享")
    var that = this;
  },
  pickerSelected: function (e) {
    let that = this;
    let status = e.currentTarget.dataset.status;
    if (status == 'job') {
      that.setData({
        job: e.detail.value
      })
    }
  },
  getStaffJob: function () {
    var that = this;
    app.util.request({
      'url': 'entry/wxapp/Job',
      'cachetime': '30',
      'method': 'POST',
      'data': {
      },
      success: function (res) {
        console.log("entry/wxapp/Job ==>", res)
        if (!res.data.errno) {
          var tmpData = res.data.data;
          var tmpJob = [];
          for (let i in tmpData) {
            tmpJob.push({ id: tmpData[i].id, name: tmpData[i].name })
          }
          that.setData({
            setJob: tmpJob
          })
        }
      },
      fail: function (res) {
        console.log("fail ==> ", res)
      }
    })
  },
  getStaffCard: function () {
    var that = this;
    app.util.request({
      'url': 'entry/wxapp/StaffCard',
      'cachetime': '30',
      'method': 'POST',
      'data': {
      },
      success: function (res) {
        // console.log("entry/wxapp/StaffCard ==>", res)
        if (!res.data.errno) {
          var tmpData = res.data.data.count;
          var tmpSetJob = that.data.setJob;

          for (let i in tmpSetJob) {
            if (tmpData.job_id == tmpSetJob[i].id) {
              that.setData({
                job: i
              })
            }
          }

          let tmpImgPath = that.data.staffInfoImages;
          for (let j in tmpData.images) {
            if (!tmpData.images[j]) {
              tmpData.images.splice(j, 1)
            }
            tmpImgPath.push(tmpData.images[j])
          }

          that.setData({
            staffInfoImages: tmpImgPath,
            staffInfo: tmpData
          })

        }
      },
      fail: function (res) {
        console.log("fail ==> ", res)
      }
    })
  },
  toEditStaff: function (paramObj) {
    var that = this;
    app.util.request({
      'url': 'entry/wxapp/EditStaff',
      'cachetime': '30',
      'method': 'POST',
      'data': paramObj,
      success: function (res) {
        // console.log("entry/wxapp/StaffCard ==>", res)
        if (!res.data.errno) {
          wx.showModal({
            title: '',
            content: '名片修改成功！',
            showCancel: false,
            success: res => {
              if (res.confirm) {
                wx.navigateBack();
              } else {
              }
            }
          });
        }
      },
      fail: function (res) {
        console.log("fail ==> ", res)
      }
    })
  },
  chooseImage: function () {
    var that = this;
    wx.showActionSheet({
      itemList: ['优雅自拍', '相册收藏'],
      itemColor: '#3675f1',
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImageShop('camera');
          } else if (res.tapIndex == 1) {
            that.chooseWxImageShop('album');
          }
        }
      },
      fail: function (res) {
        console.log("fail ==> ", res)
      }
    });
  },
  chooseWxImageShop: function (type) {
    var that = this;
    var tmpPath = that.data.staffInfo.images;
    var tmpImg = that.data.staffInfoImages;

    // var tmpPathOld = [];
    // if(tmpPath.length > 0){
    //   tmpPathOld = tmpPath;
    // }
    // var tmpImgOld = [];
    // if(tmpImg.length > 0){
    //   tmpImgOld = tmpImg;
    // }

    // console.log(tmpImg,tmpPath,"***********/////////")
    // console.log(tmpImgOld,tmpPathOld,"***********/////////")

    var tmpCount;
    if (that.data.uploadType == 'toAvatar') {
      tmpCount = 1;
    } else if (that.data.uploadType == 'toImages') {
      tmpCount = 8;
    }
    wx.chooseImage({
      count: tmpCount,
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: function (res) {
        // console.log(res, "===========================  res****")
        for (let i in res.tempFilePaths) {
          console.log(res.tempFilePaths[i], "****************//res.tempFilePaths[i]");
          wx.showLoading({
            title:'图片上传中...'
          });
          wx.uploadFile({
            url: that.data.uploadUrl,
            filePath: res.tempFilePaths[i],
            name: 'upfile',
            formData: {},
            success: function (res) {
              console.log(res, "******/////////////////////res")
              wx.hideLoading();
              var tmpData = JSON.parse(res.data);
              if (that.data.uploadType == 'toAvatar') {
                that.setData({
                  'staffInfo.avatar': tmpData.data.path,
                  staffInfoAvatar: tmpData.data.img
                })
              } else if (that.data.uploadType == 'toImages') {
                tmpPath.push(tmpData.data.path);
                tmpImg.push(tmpData.data.img);
                if (tmpPath.length > 8) {
                  wx.showModal({
                    title: '',
                    content: '最多只能上传8张图片哦！',
                    confirmText: '知道啦',
                    showCancel: false,
                    success: res => {
                      if (res.confirm) {
                      } else {

                      }
                    }
                  });
                  return false;
                }
                that.setData({
                  'staffInfo.images': tmpPath,
                  staffInfoImages: tmpImg,
                })
              }
            }
          })
        }
      },
      fail: function (res) {
        console.log("fail ==> ", res)
      }
    })
  },
  getCheckAuthRecord() {
    var that = this;
    wx.authorize({
      scope: 'scope.record',
      success(res) {
        console.log('getCheckAuthRecord 授权成功')
        that.setData({
          recordAuthMethod: 2
        })
      },
      fail() {
        that.setData({
          recordAuthMethod: 1
        })
      }
    })


    var tmpRecordStatusText = '';
    if (that.data.staffInfo.voice) {
      if (that.data.recordAuthMethod == 1) {
        tmpRecordStatusText = '重新录音 按住说话'
      } else if (that.data.recordAuthMethod == 2) {
        tmpRecordStatusText = '重新录音 按住说话'
      }
    } else if (!that.data.staffInfo.voice) {
      if (that.data.recordAuthMethod == 1) {
        tmpRecordStatusText = '开始录音 按住说话'
      } else if (that.data.recordAuthMethod == 2) {
        tmpRecordStatusText = '开始录音 按住说话'
      }
    }

    that.setData({

      recordAuthMethod: tmpRecordStatusText
    })


  },
  startRecord: function () {
    let that = this
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.record']) {
          console.log('startRecord 已经授权')
          that.toStartRecord();
        } else {
          // that.setData({
          //   recordAuthMethod: 1
          // })
          that.getCheckAuthRecord();
          console.log("getCheckAuthRecord")
        }
      },
      fail: function (res) {
        that.getCheckAuthRecord();
        console.log("getCheckAuthRecord")
        // that.setData({
        //   recordAuthMethod: 1
        // })
      }
    })
  },
  //松开按钮
  stopRecord_get: function () {
    var that = this;
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.record']) {
          that.stopRecord();
        }
      }
    })
  },
  toStartRecord: function () {
    var that = this;
    const options = {
      duration: 60000,//指定录音的时长，单位 ms
      sampleRate: 16000,//采样率
      numberOfChannels: 1,//录音通道数
      encodeBitRate: 96000,//编码码率
      format: 'mp3',//音频格式，有效值 aac/mp3
      frameSize: 50,//指定帧大小，单位 KB
    }
    console.log(recorderManager, "recorderManager")
    //开始录音
    recorderManager.start(options);
    recorderManager.onStart(() => {
      console.log('recorder start')
      that.setData({
        showTostImg : true
      })
      // wx.showToast({
      //   icon: '',
      //   image: '/longbing_card/resource/images/speak.gif',
      //   title: '松开结束',
      //   duration:60000
      // })
    });

    var tmpRecordStatusText = '';
    if (that.data.staffInfo.voice) {
      tmpRecordStatusText = '重新录音 松开结束'
    } else if (!that.data.staffInfo.voice) {
      tmpRecordStatusText = '开始录音 松开结束'
    }

    that.setData({
      tmpRecordStatusText: tmpRecordStatusText
    })
    //错误回调
    recorderManager.onError((res) => {
      console.log(res);
    })
  },
  stopRecord: function () {
    var that = this;
    recorderManager.stop();
    recorderManager.onStop((res) => {
      console.log(res, "recorder onStop") 
      that.setData({
        'staffInfo.voice': res.tempFilePath,
        'staffInfo.voice_time': (res.duration / 1000).toFixed(0),
         showTostImg : false
      })
 
      console.log("staffInfo.voice", that.data.staffInfo.voice) 
    })
    that.setData({
      startPushStatus: 1
    })
  },
  toUploadRecord(cb) {
    var that = this;
    console.log(that.data.tempRecordFilePath, "tempRecordFilePath")

    console.log("that.data.staffInfo.voice",that.data.staffInfo.voice)
    console.log("that.data.staffInfo.voice",that.data.staffInfo.voice.indexOf('wxfile://'))
    if(that.data.staffInfo.voice.indexOf('wxfile://') == -1 ){
      cb && cb();
      return ;
    }


    wx.uploadFile({
      url: that.data.uploadUrl,
      filePath: that.data.staffInfo.voice,
      name: 'upfile',
      formData: {
      },
      success: function (res) {
        console.log(res, "******/////////////////////res", that.data.tempRecordFileTime)
        var tmpData = JSON.parse(res.data);
        that.setData({
          'staffInfo.voice': tmpData.data.path,
          staffInfoVoice: tmpData.data.img,
        })
        
        cb && cb();

      },
      fail: function (res) {
        console.log("fail ==> ", res)
      }
    })
  },
  formSubmit: function (e) {
    var that = this;
    var formId = e.detail.formId;
    var status = e.detail.target.dataset.status;
    that.toSaveFormIds(formId);
    if (status == 'toEditStaff') {
      console.log("修改名片信息")
      
      that.toUploadRecord(function(){

        
        var paramObj = e.detail.value;
      var myPreg = /^[1][3,4,5,7,8][0-9]{9}$/;
      var myEreg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
      if (!myPreg.test(e.detail.value.phone)) {
        wx.showModal({
          title: '',
          content: '手机号码格式错误，请填写正确的手机号码！',
          confirmText: '知道啦',
          showCancel: false,
          success: res => {
            if (res.confirm) {
            } else {
            }
          }
        });
        return false;
      }
      if (!myEreg.test(e.detail.value.email)) {
        wx.showModal({
          title: '',
          content: '请填写正确的邮箱号码！',
          confirmText: '知道啦',
          showCancel: false,
          success: res => {
            if (res.confirm) {
            } else {
            }
          }
        });
        return false;
      }
      var tmpUpData = that.data.staffInfoImages;
      var tmpData = that.data.staffInfo.images;
      var tmpImages = '';
      var tmpAvatar = '';
      var tmpVoice = '';

      if (tmpUpData.length > 0) {
        for (let i in tmpUpData) {
          tmpImages += (tmpUpData[i] + ',')
        }
      } else {
        for (let i in tmpData) {
          tmpImages += (tmpData[i] + ',')
        }
      }

      if (!that.data.staffInfoAvatar) {
        tmpAvatar = that.data.staffInfo.avatar
      } else {
        tmpAvatar = that.data.staffInfoAvatar
      }
      if (!that.data.staffInfoVoice) {
        tmpVoice = that.data.staffInfo.voice
      } else {
        tmpVoice = that.data.staffInfoVoice
      }


      let tmpJob = '';
      if (that.data.job < 0) {
        tmpJob = '';
      } else {
        tmpJob = that.data.setJob[that.data.job].id;
      }


      tmpImages = tmpImages.slice(0, -1);
      paramObj.avatar = tmpAvatar;
      paramObj.voice = tmpVoice;
      paramObj.voice_time = that.data.staffInfo.voice_time;
      paramObj.images = tmpImages;
      paramObj.job_id = tmpJob;
      console.log(paramObj, "///////////**********")
      that.toEditStaff(paramObj);




      });


      
    }
  },
  toSaveFormIds: function (formId) {
    var that = this;
    app.util.request({
      'url': 'entry/wxapp/formid',
      'cachetime': '30',
      'showLoading': false,
      'method': 'POST',
      'data': {
        formId: formId
      },
      success: function (res) {
        // console.log("entry/wxapp/formid ==>", res)
        if (!res.data.errno) {
        }
      },
      fail: function (res) {
        console.log("fail ==> ", res)
      }
    })
  },
  toJump: function (e) {
    var that = this;
    var status = e.currentTarget.dataset.status;
    var index = e.currentTarget.dataset.index;
    var type = e.currentTarget.dataset.type;

    const innerAudioContext = wx.createInnerAudioContext();

    if (status == 'toUpload') {
      console.log("修改头像 || 图片展示")
      that.setData({
        uploadType: type
      })
      that.chooseImage();
    } else if (status == 'toVoice') {
      if (type == 1) {
        console.log("语音播放 playBackgroundAudio", that.data.staffInfo.voice)

        innerAudioContext.autoplay = true
        innerAudioContext.src = that.data.staffInfo.voice
        innerAudioContext.onPlay(() => {
          console.log('开始播放')
        }) 
        that.setData({
          playPushStatus: 2
        });
      }
      if (type == 2) {
        // console.log("语音播放 pauseBackgroundAudio")
        innerAudioContext.pause(() => {
          console.log('暂停播放')
        }) 
        that.setData({
          playPushStatus: 1
        });
      }
    } else if (status == 'toShowDelete') {
      console.log("显示删除图片按钮")
      that.setData({
        currentIndex: index
      })
    } else if (status == 'toDeleteImg') {
      console.log("删除图片")
      let tmpData = that.data.staffInfo.images;
      let tmpUpData = that.data.staffInfoImages;
      tmpUpData.splice(index, 1);
      tmpData.splice(index, 1);
      that.setData({
        'staffInfo.images': tmpData,
        staffInfoImages: tmpUpData
      })
    }

    innerAudioContext.onEnded(() => {
      console.log('音频自然播放结束事件')
      that.setData({
        playPushStatus: 1
      });
    })
  }
})